﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using XLua;

namespace Al_FrameWork
{
    public enum DownloadStatus
    {
        Done = 0, //下载成功
        Failed = 1, //下载失败
    }

    [Hotfix]
    [LuaCallCSharp]
    public class WWWManager : MonoBehaviour
    {
        private static WWWManager _instance;

        public static WWWManager Instance
        {
            get { return GlobalFunctions.GetInstance(ref _instance, "_WWWManager", true); }
        }

        private UnityWebRequest webRequest;

        private WWW wwwDownload;

        public void Download(string url, Action<WWW> done, float delay = 0)
        {
            if (done == null)
            {
                done = (WWW www) => { };
            }

            StartCoroutine(IEDownload(url, done, delay));
        }

        /// <summary>
        /// IEDownload
        /// </summary>
        /// <param name="url"></param>
        /// <param name="done"></param>
        /// <param name="delay"></param>
        /// <returns></returns>
        private IEnumerator IEDownload(string url, Action<WWW> done, float delay)
        {
            ///延迟执行
            yield return new WaitForSeconds(delay);
            using (WWW www = new WWW(url))
            {
                wwwDownload = www;
                yield return www;
                if (!string.IsNullOrEmpty(www.error))
                {
                    GlobalFunctions.Err("{0}发生www.error={1}", url, www.error);
                    done(null);
                    yield break;
                }

                if (www.isDone)
                {
                    done(www);
                }
            }
        }

        /// <summary>
        /// 后台下载
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <param name="done"></param>
        /// <param name="delay"></param>
        public void BackgroundDownload(string url, string path, Action<DownloadStatus> done, float delay = 0)
        {
            if (done == null)
            {
                done = (DownloadStatus status) => { };
            }

            StartCoroutine(OnBackgroundDownload(url, path, done, delay));
        }

        /// <summary>
        /// 后台下载
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <param name="done"></param>
        /// <param name="delay"></param>
        /// <returns></returns>
        IEnumerator OnBackgroundDownload(string url, string path, Action<DownloadStatus> done, float delay)
        {
            yield return new WaitForSeconds(delay);
            UnityWebRequest request = UnityWebRequest.Get(url);
            webRequest = request;
            request.timeout = 100;
            yield return request.SendWebRequest();
            if (request.isDone)
            {
                if (request.isHttpError || request.isNetworkError)
                {
                    print(url + "下载错误=>" + request.error);
                    done(DownloadStatus.Failed);
                }
                else
                {
                    GlobalFunctions.LOG("url={0}下载成功", url);
                    byte[] bytes = request.downloadHandler.data;
                    print("bytes下载文件的大小----" + bytes.Length);
                    GlobalFunctions.SafeWriteAllBytes(path, bytes);
                    done(DownloadStatus.Done);
                }
            }
            
            webRequest = null;
        }

        /// <summary>
        /// GetAssetBundle
        /// </summary>
        /// <param name="url"></param>
        /// <param name="done"></param>
        public void GetAssetBundle(string url, Action<AssetBundle> done)
        {
            StartCoroutine(OnLoadAssetBundle(url, done));
        }

        /// <summary>
        /// OnLoadAssetBundle
        /// </summary>
        /// <param name="url"></param>
        /// <param name="done"></param>
        /// <returns></returns>
        IEnumerator OnLoadAssetBundle(string url, Action<AssetBundle> done)
        {
            UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url, 0);
            webRequest = request;
            yield return request.SendWebRequest();

            if (request.isDone)
            {
                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                done(bundle);
            }
            else
            {
                GlobalFunctions.Err("OnLoadAssetBundle error={0}", request.error);
                done(null);
            }

            webRequest = null;
        }


        /// <summary>
        /// 获取下载进度
        /// </summary>
        /// <returns></returns>
        public float GetProcess()
        {
            if (wwwDownload != null)
            {
                return wwwDownload.progress;
            }
            else if (webRequest != null)
            {
                return webRequest.downloadProgress;
            }

            return 0;
        }
    }
}